/*
 * 用于计算wave特效按钮的点击的中心
 * @Author: ljb
 * @Date: 2018-08-31 15:29:55
 * @Last Modified by: ljb
 * @Last Modified time: 2018-09-04 15:21:34
 */

/**
 * 获取元素的内外边距之类的属性
 * @param  {Object} obj  {元素对象}
 * @param  {String} attr {需要获取的属性名称}
 * @return {String} {获取到的属性值}
 */
function getStyle(obj, attr) {
	if (obj.currentStyle) {
		return obj.currentStyle[attr];
	}

	return document.defaultView.getComputedStyle(obj, null)[attr];
}

/**
 * 创建元素以及删除元素
 * @param  {Object} btn      {父级的btn}
 * @param  {Object} position {创建好的元素的宽高和left、top属性}
 * @return {undefined}
 */
function createElement(btn, position) {
	const span = document.createElement('span');

	btn.appendChild(span);

	span.style.width = position.width;
	span.style.height = position.height;

	span.style.left = position.x;
	span.style.top = position.y;

	span.setAttribute('class', 'wave-effect-container wave-effect-animation');

	setTimeout(() => {
		btn.removeChild(span);
	}, 800);
}

/**
 * 计算创建的元素的宽高和left、top
 * @param  {Object} e {传进来的事件对象}
 * @return {Object} {创建的元素的宽高和left、top}
 */
function countLeftAndTop(e) {
	const btn = e.target;

	const mouse_x = e.clientX || e.pageX;	// 鼠标x轴
	const mouse_y = e.clientY || e.pageY; // 鼠标y轴

	const button_left = e.target.offsetLeft; // 按钮距离左边距离
	const button_top = e.target.offsetTop; // 按钮距离顶部距离

	const scroll_top = window.scrollY; // 窗口滚动的高度

	const button_paddingTop = parseInt(getStyle(btn, 'paddingTop'), 10);
	const button_paddingBottom = parseInt(getStyle(btn, 'paddingBottom'), 10);
	const button_paddingLeft = parseInt(getStyle(btn, 'paddingLeft'), 10);
	const button_paddingRight = parseInt(getStyle(btn, 'paddingRight'), 10);

	const button_width = e.target.offsetWidth + button_paddingLeft + button_paddingRight; // 按钮总宽度
	const button_height = e.target.offsetHeight + button_paddingTop + button_paddingBottom; // 按钮总高度

	const wave_r = Math.max(parseInt(button_width, 10), parseInt(button_height, 10)); // 初始化波浪的半径为按钮宽度、高度之中的最大值;

	const x_offset = mouse_x - button_left - wave_r; // 波浪效果的span的x轴的偏移量
	const y_offset = (mouse_y - button_top - wave_r) + scroll_top; // 波浪效果的span的y轴的偏移量

	return {
		width: `${2 * wave_r}px`,
		height: `${2 * wave_r}px`,
		x: `${x_offset}px`,
		y: `${y_offset}px`,
	};
}

/**
 * 给wave-button增加元素监听
 * @return {undefined}
 */
const wave = function wave() {
	const wave_buttons = document.querySelectorAll('.wave-button');

	wave_buttons.forEach((wave_button) => {
		wave_button.addEventListener('click', (e) => {
			const position = countLeftAndTop(e);
			createElement(wave_button, position);
		});
	});
};

export default wave;
